package com.tencent.crazypenguin.action;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.tencent.crazypenguin.bean.User;
import com.tencent.crazypenguin.config.ResultType;
import com.tencent.crazypenguin.dao.UserDao;
import com.tencent.crazypenguin.util.ConfigUtil;
import com.tencent.crazypenguin.util.JsonUtil;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import net.sf.json.JSONObject;

public class Login extends ActionSupport {

	/**
	 * by pluschen 2016-6-25
	 */
	private static final long serialVersionUID = 4738393664525958473L;
	private String result; 

	@Override
	public String execute() throws Exception {
		
		JSONObject rspData = new JSONObject();
		try {
			UserDao userDao = new UserDao();
			String loginName = null;
			String passWord = null;
			String devId = null;
			
			
			JSONObject postJson = JsonUtil.getPostData();
			
			
			loginName = postJson.getString("loginName");
			passWord = postJson.getString("passWord");
			devId = postJson.getString("devId");
			
			int iResult = userDao.authority(loginName,passWord);
			rspData.put("resultCode", iResult);
			
			if(iResult == ResultType.SUCEESS){
				HttpServletRequest request = ServletActionContext.getRequest();
				User user = (User) request.getAttribute("user");
				user.setDev_id(devId);
				userDao.update(user);
				rspData.put("token", createJWT(user.getId()+"","crazypenguin",devId,7200000));
				rspData.put("user", JSONObject.fromObject(user));
			}
			result = rspData.toString();
			return "done";
		} catch (Exception e) {
			e.printStackTrace();
			rspData.put("resultCode", ResultType.EXCEPTION);
			result = rspData.toString();
			return "done";
		}
	}
	
	private String createJWT(String userName, String issuer, String subject, long ttlMillis) {
		 
		//The JWT signature algorithm we will be using to sign the token
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		 
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		 
		//We will sign our JWT with our ApiKey secret
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(ConfigUtil.iGetConfig("tokenKey"));
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		 
		  //Let's set the JWT Claims
		JwtBuilder builder = Jwts.builder().setId(userName)
		                                .setIssuedAt(now)
		                                .setSubject(subject)
		                                .setIssuer(issuer)
		                                .signWith(signatureAlgorithm, signingKey);
		 
		 //if it has been specified, let's add the expiration
		if (ttlMillis >= 0) {
		    long expMillis = nowMillis + ttlMillis;
		    Date exp = new Date(expMillis);
		    builder.setExpiration(exp);
		}
		 
		 //Builds the JWT and serializes it to a compact, URL-safe string
		return builder.compact();
		}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

}
